#include "server.h"

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h> //增加这个 64位下调用inet_ntoa才不会报错
#include"debug_print.h"

extern int errno;

int server()
{

    int fd_server_socket;//服务器套接字
    struct sockaddr_in server_addr;//服务器地址
    struct sockaddr_in client_addr;//客户端地址
 
	//------------------- 创建socket -------------------//
	//AF_INET 		ipv4
	//SOCK_STREAM 	数据流模式
	//第三个参数protocol 一般为0
	DEBUG_PRINT("creat socket\r\n");
    if ((fd_server_socket = socket(AF_INET, SOCK_STREAM, 0))  < 0)
	{
        perror("creat socket failed!\r\n");
		printf("error code: %d \r\n message: %s \r\n",errno,strerror(errno));
        return -1;
    }
 	//清空结构体
    memset(&server_addr, 0,sizeof(server_addr));
 
    server_addr.sin_family = AF_INET; //协议选ipv4
    server_addr.sin_port = htons(SERVER_PORT);//服务器监听的端口号，转为网络字节序 hons 短整型转为网络字节序  honl长整型
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//服务器IP地址，INADDR_ANY为通配地址，转为网络字节序
 

 	//------------------- 绑定socket -------------------//
 	DEBUG_PRINT("bind socket\r\n");
    if (bind(fd_server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) != 0) 
	{
        perror("bind socket failed!\r\n");
		printf("error code: %d \r\n message: %s \r\n",errno,strerror(errno));
        return -1;
    }
 
    //------------------- 监听 -------------------//
    //10 内核为此套接字排队的最大连接个数
    DEBUG_PRINT("listen \r\n");
    if (listen(fd_server_socket, MAX_LENGTH_QUENES) != 0) 
	{
        DEBUG_PRINT("listen error\r\n");
		DEBUG_PRINT("error code: %d \r\n message: %s \r\n",errno,strerror(errno));
        return -1;
 
    }
    DEBUG_PRINT("server port: %d\r\n", SERVER_PORT);
	
    int i = 1;

	while (1) 
	{	
     	//------------------- 接受客户端连接请求 -------------------//
     	int addr_len = sizeof(client_addr);
        int client = accept(fd_server_socket, (struct sockaddr *) &client_addr, (socklen_t *) &addr_len);
 
        if (client < 0)
		{
            DEBUG_PRINT("accept client failed\r\n");
			DEBUG_PRINT("error code: %d \r\n message: %s \r\n",errno,strerror(errno));
            continue;
        }
		DEBUG_PRINT("\r\n");
		DEBUG_PRINT("accept client: %d\r\n",i++);
 		//打印客户端信息
        char* ip_client = inet_ntoa(client_addr.sin_addr);
 		DEBUG_PRINT("client ip: %s \r\n",inet_ntoa(client_addr.sin_addr));//inet_ntoa 将网络字节序转为点分十进制
 		DEBUG_PRINT("client port: %d \r\n",htons(client_addr.sin_port));//htons将网络字节序转为十进制
 
    }
 
    close(fd_server_socket);
    return 0;


}
